package com.mall.controller;

import com.mall.websocket.SendChatEO;
import com.mall.websocket.SendMsgEO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.security.Principal;

@Controller
public class ChatRoomController {

   @Autowired
   private SimpMessagingTemplate SimpMessagingTemplate;


   @GetMapping("/chatroom")
   public String chatroom(Model m) {
      return "chatroom";
   }
   @GetMapping("/chatroom2")
   public String chatroom2(Model m) {
      return "chatroom2";
   }


   /**
    * 点对点发送消息
    * @param m
    * @return
    */
   @GetMapping("/chatroom3")
   public String chatroom3(Model m) {
      return "chatroom3";
   }


   /**
    * @MessageMapping（"/hello"）注解的方法将用来接收"/app/hello路径发送来的消息，<br/>
    * 在注解方法中对消息进行处理后，再将消息转发到 @SendTo 定义的路径上，而@SendTo路径是个前缀为"/topic"的路径，<br/>
    * 因此该消息将被交给消息代理 broker ，再由 broker 进行广播。
    */
   @MessageMapping("/hello")
   @SendTo("/topic/greetings")
   public SendMsgEO greeting(SendMsgEO message) throws Exception {
      return message;
   }

   @MessageMapping("/chat")
   public void chat(Principal principal, SendChatEO chat) {
      String from = principal.getName();
      chat.setFrom(from);
      SimpMessagingTemplate.convertAndSendToUser(chat.getTo(), "/queue/chat", chat);
   }

}



